package tags;

import java.io.File;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;

public class Mp3Tags {

	public static String getArtist(File mp3) {

		AudioFile f = null;
		try {
			f = AudioFileIO.read(mp3);
		} catch (Throwable e) {
			printErrorLn("Cannot read mp3 file :\"" + mp3.getAbsolutePath()
					+ "\"");
			e.printStackTrace();
		}
		Tag tag = f.getTag();
		if (tag == null) {
			printErrorLn("No tag to edit");
			System.exit(1);
		}
		String value = tag.getFirst(FieldKey.ARTIST);
		if (value == null) {
			value = "";
		}
		
		return value;

	}

	private static void printErrorLn(String message) {
		System.err.println("COMPUTER ERROR : " + message);
	}

	public static void setArtist(File mp3, String artist) {
		setField(FieldKey.ARTIST, mp3, artist);
	}

	public static void setGenre(File tempMp3, String genre) {
		setField(FieldKey.GENRE, tempMp3, genre);
	}

	public static void setTitle(File mp3, String title) {
		setField(FieldKey.TITLE, mp3, title);
	}
	
	public static void setField(FieldKey fieldKey, File mp3, String value) {

		AudioFile f = null;
		try {
			f = AudioFileIO.read(mp3);
		} catch (Throwable e) {
			printErrorLn("Cannot read mp3 file :\"" + mp3.getAbsolutePath()
					+ "\"");
			e.printStackTrace();
		}
		Tag tag = f.getTag();
		try {
			tag.setField(fieldKey, value);
		} catch (Throwable e) {
			printErrorLn("Cannot set field author");
			e.printStackTrace();
		}
		try {
			f.commit();
		} catch (CannotWriteException e) {
			printErrorLn("Cannot write to file \"" + mp3.getAbsolutePath()
					+ "\"");
			e.printStackTrace();
		}
	}

	public static String getRating(File mp3) {
		AudioFile f = null;
		try {
			f = AudioFileIO.read(mp3);
		} catch (Throwable e) {
			printErrorLn("Cannot read mp3 file :\"" + mp3.getAbsolutePath()
					+ "\"");
			e.printStackTrace();
		}
		Tag tag = f.getTag();
		if (tag == null) {
			printErrorLn("No tag to edit");
			System.exit(1);
		}
		String value = tag.getFirst(FieldKey.RATING);
		if (value == null) {
			value = "";
		}
		
		return value;
	}

	public static void setRating(File mp3, String rating) {
		setField(FieldKey.RATING, mp3, rating);
	}

}
